import unittest
import AccountClient
import Account_pb2


class GrpcClientTest(unittest.TestCase):
    def setUp(self) -> None:
        self.client = AccountClient.AccountClient(target='127.0.0.1:58080')
        self.id_string = "id"
        self.email_string = "email"
        self.balance_string = "balance"
        self.accounts = {}
        # 为了不引入数据库，直接构造同服务端data.sql内容一样的数据
        for i in range(1, 7):
            self.accounts[i] = Account_pb2.Account(id=i, email="id"+str(i)+"@foxmail.com", balance=20+i)

    def testUnaryRPC(self):
        target_id = 3
        target_account = self.accounts.get(target_id)
        response_account = self.client.findOneById(target_id)
        self.assertEqual(response_account.id, target_account.id)
        self.assertEqual(response_account.email, target_account.email)
        self.assertEqual(response_account.balance, target_account.balance)

    def testServerStreamingRPC(self):
        lower = 1
        upper = 3
        accounts = self.client.findAllByRange(lower, upper)
        for account in accounts:
            target_account = self.accounts.get(account.id)
            self.assertEqual(account.id, target_account.id)
            self.assertEqual(account.email, target_account.email)
            self.assertEqual(account.balance, target_account.balance)

    def testClientStreamingRPC(self):
        test_ids = [1, 2, 3]
        target_sum = 0
        for i in test_ids:
            target_sum += self.accounts.get(i).balance
        response = self.client.getBalanceSumByIds([1, 2, 3])
        self.assertEqual(response.balanceSum, target_sum)

    def testBidirectionalStreamingRPC(self):
        test_ids = [1, 2, 3]
        response_accounts = self.client.findAllByIds(test_ids)
        for account in response_accounts:
            self.assertIn(account.id, test_ids)
            target_account = self.accounts.get(account.id)
            self.assertEqual(account.email, target_account.email)
            self.assertEqual(account.balance, target_account.balance)


